package com.example.rdb.handle.mysql;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.rdb.conf.ConfigInfo;
import com.example.rdb.conf.Constants;
import com.example.rdb.handle.mysql.entity.SourceMaterial;
import com.example.rdb.handle.mysql.read.CmsReadMapper;
import com.example.rdb.handle.mysql.write.BiWriteMapper;
import com.example.rdb.handle.mysql.write.CmsWriteMapper;
import com.example.rdb.handle.mysql.write.MpWriteMapper;
import com.example.rdb.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.*;

/**
 * @author XYC
 * @描述: TODO
 * @date 21.5.2817:32
 */
@Component
@Slf4j
public class MysqlMoveOne {

    @Autowired
    @Qualifier(value = "cmsWriteSqlSessionTemplate")
    private SqlSessionTemplate cmsWriteSqlSessionTemplate;

    @Autowired
    @Qualifier(value = "cmsReadSqlSessionTemplate")
    private SqlSessionTemplate cmsReadSqlSessionTemplate;

    @Autowired
    @Qualifier(value = "biWriteSqlSessionTemplate")
    private SqlSessionTemplate biWriteSqlSessionTemplate;

    @Autowired
    @Qualifier(value = "mpWriteSqlSessionTemplate")
    private SqlSessionTemplate mpWriteSqlSessionTemplate;


    public void mysqlMove() throws Exception {
        System.out.println("------MYSQL-START------");
        //内容管理写入素材表cms_source_material
        insertSourceMaterial();
        //安全管理数据写入cms_exception_info
        insertCmsDatabase("cms_exception_info","id",true);
        //安全管理数据写入cms_security_policy
        insertCmsDatabase("cms_security_policy","id",true);
        //数据采集数据写入page_name_config
        insertBiDatabase("bi_page_name_config","page_id",true);
        //数据采集数据写入collect_event_data
        insertBiDatabase("bi_collect_event_data","id",false);
//        //微信管理数据写入wx_account
//        insertMpDatabase("wx_account","id","tenant_id",true);
//        //微信管理数据写入wx_fans_msg
//        insertMpDatabase("wx_account_fans","id","tenant_id",true);
//        //微信管理数据写入wx_mp_menu
//        insertMpDatabase("wx_mp_menu","id","tenant_id",true);
//        //微信管理数据写入wx_app
//        insertMpDatabase("wx_app","id","wx_id",true);
        System.out.println("------MYSQL-END------");
    }
    public void mysqlMoveByJson() throws Exception {
        System.out.println("------MYSQL-START------");
        //内容管理写入素材表cms_source_material
        insertSourceMaterialByJson();
//        //安全管理数据写入cms_exception_info
//        insertCmsDatabase("cms_exception_info","id",true);
//        //安全管理数据写入cms_security_policy
//        insertCmsDatabase("cms_security_policy","id",true);
//        //数据采集数据写入page_name_config
//        insertBiDatabase("bi_page_name_config","page_id",true);
//        //数据采集数据写入collect_event_data
//        insertBiDatabase("bi_collect_event_data","id",false);
//        //微信管理数据写入wx_account
//        insertMpDatabase("wx_account","id","tenant_id",true);
//        //微信管理数据写入wx_fans_msg
//        insertMpDatabase("wx_account_fans","id","tenant_id",true);
//        //微信管理数据写入wx_mp_menu
//        insertMpDatabase("wx_mp_menu","id","tenant_id",true);
//        //微信管理数据写入wx_app
//        insertMpDatabase("wx_app","id","wx_id",true);
        System.out.println("------MYSQL-END------");
    }



    public void delete() throws Exception {
        System.out.println("------MYSQL-DELETE-START------");
        BiWriteMapper biWriteMapper = biWriteSqlSessionTemplate.getMapper(BiWriteMapper.class);
        CmsWriteMapper cmsWriteMapper = cmsWriteSqlSessionTemplate.getMapper(CmsWriteMapper.class);
        MpWriteMapper mpWriteMapper = mpWriteSqlSessionTemplate.getMapper(MpWriteMapper.class);
        //bi数据清除
        biWriteMapper.deleteDataByAppId(ConfigInfo.appWrite);
        //cms数据清除
        cmsWriteMapper.deleteDataByAppId(ConfigInfo.appWrite);
        //mp数据清除
//        mpWriteMapper.deleteDataByTenantId(ConfigInfo.tenantWrite);
        System.out.println("------MYSQL-DELETE-END------");

    }


    private void insertBiDatabase(String table,String id,boolean isAdd) {
        BiWriteMapper biWriteMapper = biWriteSqlSessionTemplate.getMapper(BiWriteMapper.class);
        //获取json数据
        String jsonStr = JsonUtils.readJsonFile(new File(table+".json"));
        JSONArray jsonArray = JsonUtils.jsonStrToArray(table,jsonStr);
        List<Map<String,Object>> list = (List)jsonArray;
        int num = RandomUtil.randomInt(1000000,99999999);
        if(isAdd){
            num = (biWriteMapper.getBiDatabaseNum(table, id)) == null ? 1 : (biWriteMapper.getBiDatabaseNum(table, id) + 1);
        }
        //获取表字段
        Set<String> cols = list.get(0).keySet();
        for (Map map : list) {
            map.put(id,num ++);
            map.put("app_id",ConfigInfo.appWrite);
            if (cols.contains("create_time")){
                map.put("create_time",new DateTime());
            }
            if (cols.contains("update_time")){
                map.put("update_time",new DateTime());
            }
        }
//        log.info("数据采集数据-"+table+":"+list.toString());
        //写入
        biWriteMapper.batchBiInsertData(table,cols,list);
        log.info("数据采集数据"+table+"写入完成");
    }

    private void insertCmsDatabase(String table,String id,boolean isAdd) {
        CmsWriteMapper cmsWriteMapper = cmsWriteSqlSessionTemplate.getMapper(CmsWriteMapper.class);
        //获取json数据
        String jsonStr = JsonUtils.readJsonFile(new File(table+".json"));
        JSONArray jsonArray = JsonUtils.jsonStrToArray(table,jsonStr);
        List<Map<String,Object>> list = (List)jsonArray;
        int num = RandomUtil.randomInt(1000000,99999999);
        if(isAdd){
            num = (cmsWriteMapper.getCmsDatabaseNum(table, id)) == null ? 1 : (cmsWriteMapper.getCmsDatabaseNum(table, id) + 1);
        }
        //获取表字段
        Set<String> cols = list.get(0).keySet();
        for (Map map : list) {
            map.put(id,num ++);
            map.put("app_id", ConfigInfo.appWrite);
            if (cols.contains("create_time")){
                map.put("create_time",new DateTime());
            }
            if (cols.contains("update_time")){
                map.put("update_time",new DateTime());
            }
        }
//        log.info("内容管理数据-"+table+":"+list.toString());
        //写入
        cmsWriteMapper.batchCmsInsertData(table,cols,list);
        log.info("内容管理数据"+table+"写入完成");
    }

    private void insertSourceMaterial() {
        CmsReadMapper cmsReadMapper = cmsReadSqlSessionTemplate.getMapper(CmsReadMapper.class);
        CmsWriteMapper cmsWriteMapper = cmsWriteSqlSessionTemplate.getMapper(CmsWriteMapper.class);
        SourceMaterial read = new SourceMaterial();
        read.setTenant_id(Integer.parseInt(ConfigInfo.tenantRead));
        read.setApp_id(ConfigInfo.appRead);
        //读取
        int num = cmsWriteMapper.getSourceMaterialNum()==null ? 1 : cmsWriteMapper.getSourceMaterialNum() + 1;
        List<SourceMaterial> readList = cmsReadMapper.getSourceMaterial(read);
        //读取和写入id映射
        HashMap<Integer,Integer> map = new HashMap<>();
        map.put(0,0);//根目录
        for (SourceMaterial sourceMaterial : readList) {
            map.put(sourceMaterial.getId(), num++);
        }
        readList.forEach(i ->{
            i.setId(map.get(i.getId()));
            i.setFolder_id(map.get(i.getFolder_id()));
            i.setUpdate_user(Constants.CREAT_EUSER);
            i.setCreate_user(Constants.CREAT_EUSER);
            i.setTenant_id(Integer.parseInt(ConfigInfo.tenantWrite));
            i.setApp_id(ConfigInfo.appWrite);
            i.setCreate_time(new DateTime());
            i.setUpdate_time(new DateTime());
        });
//        log.info("map;:"+map.toString());
//        log.info("list:"+readList.toString());
        //写入
        cmsWriteMapper.insterSourceMaterial(readList);
        log.info("mysql-素材写入完成");
    }

    private void insertSourceMaterialByJson() {
        System.out.println("------MYSQL-CREATE-JSON-START------");
        CmsWriteMapper cmsWriteMapper = cmsWriteSqlSessionTemplate.getMapper(CmsWriteMapper.class);
        //获取json数据
        String jsonStr = JsonUtils.readJsonFile(new File("cms_source_material.json"));
        JSONArray jsonArray = JsonUtils.jsonStrToArray("cms_source_material",jsonStr);
        List<SourceMaterial> readList = new ArrayList<>();
        int num = cmsWriteMapper.getSourceMaterialNum()==null ? 1 : cmsWriteMapper.getSourceMaterialNum() + 1;
        //读取和写入id映射
        HashMap<Integer,Integer> map = new HashMap<>();
        map.put(0,0);//根目录
        for (Object obj : jsonArray) {
            SourceMaterial  sourceMaterial = JSONUtil.toBean((JSONObject) obj,SourceMaterial.class);
            map.put(sourceMaterial.getId(), num++);
            readList.add(sourceMaterial);
        }
        readList.forEach(i ->{
            i.setId(map.get(i.getId()));
            i.setFolder_id(map.get(i.getFolder_id()));
            i.setUpdate_user(Constants.CREAT_EUSER);
            i.setCreate_user(Constants.CREAT_EUSER);
            i.setTenant_id(Integer.parseInt(ConfigInfo.tenantWrite));
            i.setApp_id(ConfigInfo.appWrite);
            i.setCreate_time(new DateTime());
            i.setUpdate_time(new DateTime());
        });
//        log.info("map;:"+map.toString());
//        log.info("list:"+readList.toString());
        //写入
        cmsWriteMapper.insterSourceMaterial(readList);
        log.info("mysql-素材写入完成");
        System.out.println("------MYSQL-CREATE-JSON-END------");
    }

    private void insertMpDatabase(String table,String id,String copyId,boolean isAdd) {
        MpWriteMapper mpWriteMapper = mpWriteSqlSessionTemplate.getMapper(MpWriteMapper.class);
        //获取json数据
        String jsonStr = JsonUtils.readJsonFile(new File(table+".json"));
        JSONArray jsonArray = JsonUtils.jsonStrToArray(table,jsonStr);
        List<Map<String,Object>> list = (List)jsonArray;
        int num = RandomUtil.randomInt(1000000,99999999);;
        if(isAdd){
            num = (mpWriteMapper.getMpDatabaseNum(table, id)) == null ? 1 : (mpWriteMapper.getMpDatabaseNum(table, id) + 1);
        }
        int copyValue = Integer.parseInt(ConfigInfo.wxTenant);
        if(copyId.equals("wx_id")){//wx_app wx_id获取
            copyValue = mpWriteMapper.getWxId(ConfigInfo.wxTenant);
        }
        //获取表字段
        Set<String> cols = list.get(0).keySet();
        for (Map map : list) {
            map.put(id,num ++);
            map.put(copyId,copyValue);
            if(copyId.equals("wx_id")){//微信对应app_id
                map.put("app_id",ConfigInfo.wxApp);
            }
            if (cols.contains("create_time")){
                map.put("create_time",new DateTime());
            }
            if (cols.contains("update_time")){
                map.put("update_time",new DateTime());
            }
        }
        //写入
        mpWriteMapper.batchMpInsertData(table,cols,list);
        log.info("微信数据"+table+"写入完成");
    }

    public void createJson() throws IOException {
        System.out.println("------Mysql-CREATE-JSON-Start------");
        CmsReadMapper cmsReadMapper = cmsReadSqlSessionTemplate.getMapper(CmsReadMapper.class);
//        CmsWriteMapper cmsWriteMapper = cmsWriteSqlSessionTemplate.getMapper(CmsWriteMapper.class);
        SourceMaterial read = new SourceMaterial();
        read.setTenant_id(Integer.parseInt(ConfigInfo.tenantRead));
        read.setApp_id(ConfigInfo.appRead);
        //读取
        int num = ConfigInfo.cmsId == null ? 0 : Integer.valueOf(ConfigInfo.cmsId);
        List<SourceMaterial> readList = cmsReadMapper.getSourceMaterial(read);
        //读取和写入id映射
        HashMap<Integer,Integer> map = new HashMap<>();
        map.put(0,0);//根目录
        for (SourceMaterial sourceMaterial : readList) {
            map.put(sourceMaterial.getId(), num++);
        }
        readList.forEach(i ->{
            i.setId(map.get(i.getId()));
            i.setFolder_id(map.get(i.getFolder_id()));
            i.setUpdate_user(Constants.CREAT_EUSER);
            i.setCreate_user(Constants.CREAT_EUSER);
            i.setTenant_id(Integer.parseInt(ConfigInfo.tenantWrite));
            i.setApp_id(ConfigInfo.appWrite);
            i.setCreate_time(new DateTime());
            i.setUpdate_time(new DateTime());
        });
//        log.info("map;:"+map.toString());
//        log.info("list:"+readList.toString());
        //写入 RECORDS
        HashMap<String,Object> records = new HashMap<>();
        records.put("RECORDS",readList);
        JSONObject jsonObject = JSONUtil.parseObj(records);
        OutputStreamWriter out = null;
        try {
            out = new OutputStreamWriter(new FileOutputStream("cms_source_material.json"),"utf-8");
            out.write(jsonObject.toString());
            out.flush();//清空缓冲区，强制输出数据
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            out.close();//关闭输出流
        }
        System.out.println("------Mysql-CREATE-JSON-END------");

    }
}
